// 引入接口文件
import { addFun,getFirst,queryInfo,findProduct,queryAllAddress,addlittle} from './soilFilmMarketDetailServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
import { makeAddress } from "utils/util"
import { rstr2b64 } from '../../../../utils/md5'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import {isEmpty, isArray, cloneDeep, merge} from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'

// 初始默认状态
const defultState = {
  btnLoading: false,
  tempId: '',
  loading: false,
  actionType: 'add',
  Mapmodel: false,//地图弹出框
  attributeList: [],
  cityList: [],
  newProduct:'',
  brandModal:{
    visible: false
  },
  paramsObj:{
    houseTypeName: ['',''],
    latAndLon: [],//经纬度['plan', 'effect', 'realScene', 'periphery', 'poster','building']
  },
  query: {
    id: '',
    attributeItem:{
      tableName: '土拍市场',
      itemValue: ''
    },
  }
}

// 声明module
const tmpModule = {
  namespace: 'defaultModel',
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({ pathname, query }) => {
        // 页面路由匹配时执行
        if('' + tmpModule.pathname === '' + pathname){
          // 执行业务操作
          dispatch({ type: 'updateStore', payload: { ...cloneDeep(defultState), ...query } })//每次进去页面先重置状态
          if(query.actionType == 'check'|| query.actionType == 'edit'){
            dispatch({type: 'queryInfo',payload: {id:query.id}})
          }
          if(query.actionType !='check'&& query.actionType != 'edit'){
            dispatch({type: 'getFirst',payload: {}})
          }
          dispatch({type: 'findProduct',payload: {}})
          dispatch({ type: 'getAreaList', payload: {} });
        } // end if
      }) // end listen
    },
  },

  // 方法列表
  effects: {
    *addlittle({payload},{put,select,call}){
      let params = { 
        id: payload.id,
        itemContent: payload.itemContent
      }
      const { success} = yield call(addlittle, {...params})
      if(success){}
    },
    *getAreaList({ payload }, { put, call, select }) {
        const data = yield call(queryAllAddress, {})
        //todo data.success //接口格式需要调整
        if (data.success) {
            let cityList = []
            let arr = [data.data[0]]
            let attr = [data.data[data.data.length - 1]]
            data.data[0] = {
                label: "北京",
                value: "110100",
                children: arr
            }
            data.data[data.data.length - 1] = {
                label: "澳门",
                value: "820000",
                children: attr
            }
            //去掉第三级，
            cityList = makeAddress(data.data, 2)
            for(var item of cityList){
                item.value = item.label
                if(item.children){
                    for(var itt of item.children){
                        itt.value = itt.label
                    }
                }
            }
            yield put({ type: 'updateStore', payload: { cityList } });
        }
    },
      *getFirst({payload}, {put, select, call}){
        let {attributeList} = yield select(state => state[tmpModule.namespace])
        let params = { 
          type: '土拍市场'
        }
        const { success,attribute} = yield call(getFirst, {...params})
        attributeList = attribute
        yield put({
          type: 'updateStore',
          payload: {attributeList}
        })
      },
      // 查询记录
      *queryInfo({payload}, {put, select, call}){
          let {query,attributeList,paramsObj} = yield select(state => state[tmpModule.namespace])
          let params = { 
            id: payload.id,
          }
          const { success,result} = yield call(queryInfo, {...params})
          if(success){
            query = result
            paramsObj.latAndLon
            paramsObj.latAndLon[0] =  Number(query.lng)
            paramsObj.latAndLon[1] = Number(query.lat)
            attributeList = JSON.parse(result.attributeItem.itemValue)
            for(var item of attributeList){
              if(item.attributeName == "地块周边价格区间（元/㎡）"||item.attributeName == "城市"){
                  item.defaultValue = item.defaultValue.split("~")
              }
            }
            yield put({
              type: 'updateStore',
              payload: {query,attributeList,paramsObj}
            })
          }
      },
      *submit({payload},{put,select,call}){
        let {query,attributeList,paramsObj,btnLoading} = yield select(state => state[tmpModule.namespace])
        let list =  attributeList.filter(item => !!item.tableField)
        for(var i = 0; i < list.length; i++){
          query[list[i].tableField] = list[i].defaultValue
        }
        query.areaName = query.areaName[1]
        query.lng  =  paramsObj.latAndLon[0]
        query.lat = paramsObj.latAndLon[1]
        query.averagePrice = query.averagePrice[0]+ '~'+query.averagePrice[1]
        for(var item of attributeList){
          if(item.attributeName == "地块周边价格区间（元/㎡）"||item.attributeName == "城市"){
            item.defaultValue = item.defaultValue[0]+ '~'+item.defaultValue[1]
          }
        }
        query.attributeItem.itemValue = JSON.stringify(attributeList)
        let params = query
        btnLoading = true

        yield put({type: 'updateStore', payload: {btnLoading}})
        let { success, msg, data } = yield call(addFun, {...params})
        let flag = success.toString()
        if(flag){
          btnLoading = false
          yield put({type: 'updateStore', payload: {btnLoading}})
        }
        if(success){
          message.success('提交成功')
          hashHistory.push({
            pathname: '/home/predictManage/soilFilmMarket',
            query: {}
          })
        }
      }
  },

  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
